<template>
    <el-select
        :disabled="listLoading"
        v-model="modelValue"
        :placeholder="config.placeholder"
        :multiple="config.multiple"
        filterable
        clearable
        >
        <el-option v-for="(op, i) in options" :key="i" :label="op.label" :value="op.value"></el-option>
    </el-select>
</template>

<script>

import { autoRequest } from '@/api/page'

export default {

    props: {
        config: {
            type: Object
        },
        value: {},
    },
    computed: {
        modelValue: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            }
        }
    },
    data() {
        return {
            listLoading: true,
            options: []
        }
    },
    watch: {
        config(val) {
            this.getOptions()
        },
    },
    mounted() {
        this.getOptions()
    },

    methods: {
        getOptions() {
            let that = this;
            this.listLoading = true
            if (!this.config) {
                return
            }
            let requestParams = {}
            if (this.config.requestParams) {
                const raw = eval( '`' +this.config.requestParams+ '`')
                requestParams = JSON.parse(raw)
            }
            autoRequest(this.config.api, 'get', requestParams, null).then(resp=> {
              let list = []
              if (that.config.listKey){
                list = resp.data[that.config.listKey]
              }else{
                list = resp.data
              }
              let options = []
              list.forEach(item => {
                  options.push(
                      {
                          label: item[that.config.labelKey],
                          value: item[that.config.valueKey]
                      }
                  )
              })
              that.options = options
              that.listLoading = false
            })
        }
    }

}
</script>
